from flask_restful import Resource, reqparse,request
from ....Model.Models import Comment as CommentModel
from ....Model.Models import Information as InformationModel
from ....Model.Models import Support as SupportModel
from ....Model.Models import UnSupport as UnSupportModel
from ....Model.Models import Report as ReportModel
from ....Model.Models import User as UserModel
from ....utils import timestamp,response,verifytoken
from flask_restful import reqparse, abort, Api, Resource, fields,\
    marshal_with
from flask_restful_swagger import swagger
success = 1
notfond = -1
error = 0

examine = 0
Online = 1
Offline = -1

token_invalid = 1000
"""
获取评论列表
"""

class createInformation(Resource):
    def __init__(self, db, auth=None):
        self.db = db

    
    @swagger.operation(
        notes='创建资讯',
        parameters=[
            {
            "name": "title",
            "description": "标题",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "content",
            "description": "内容",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "picture",
            "description": "图片url",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "create_user_id",
            "description": "创建人",
            "dataType": 'int',
            "paramType": "form"
          },
           {
            "name": "postcodes",
            "description": "邮编",
            "dataType": 'string',
            "paramType": "form"
          },
          {
            "name": "place",
            "description": "地点",
            "dataType": 'string',
            "paramType": "form"
          },
          {
            "name": "coordinate_x",
            "description": "x坐标",
            "dataType": 'string',
            "paramType": "form"
          },
          {
            "name": "coordinate_y",
            "description": "y坐标",
            "dataType": 'string',
            "paramType": "form"
          },
        {
            "name": "token",
            "description": "user_token",
            "dataType": 'string',
            "paramType": "form"
          },
      ],
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def post(self):
        try:
            args = request.form #获取表单数据
            if(verifytoken(args['token'])):#验证token值
                #插入数据
                self.db.session.add(
                    InformationModel(
                        title=args['title'],
                        content=args['content'],
                        picture=args['picture'],
                        create_user_id=(args['create_user_id']),
                        support = 0,
                        unsupported=0,
                        postcodes=args['postcodes'],
                        place=args['place'],
                        coordinate_x=args['coordinate_x'],
                        coordinate_y=args['coordinate_y'],
                        state=examine,
                        update_at=timestamp(),
                        create_at=timestamp()
                    )
                )
                self.db.session.commit()
                return response(success,None,None)
            else:
                return response(token_invalid,'登陆超时',None)
        except Exception as er:
            return response(error,er,None)

"""
通过邮编获取资讯列表
"""
class getInformationlistByPostcodes(Resource):
    def __init__(self, db, auth=None):
        self.db = db

    @swagger.operation(
        notes='通过邮编获取资讯列表',
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def get(self,postcodes,token):
        try:
           
            if(verifytoken(token)):#验证token值是否过期
                #查询所有的线上的并且邮编为postcodes的资讯
                list  = [each.as_dict() for each in self.db.session.query(InformationModel).filter_by(postcodes=postcodes,state = 1).all()]
                return response(success,None,list)
            return response(token_invalid,None,None)
        except Exception as er:
            return response(error,er,None)

"""
通过创建人获取资讯列表
"""
class getInformationlistByUserId(Resource):
    def __init__(self, db, auth=None):
        self.db = db
    
    @swagger.operation(
        notes='通过用户id查询资讯',
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def get(self,create_user_id,token):
        try:
           
            if(verifytoken(token)):#验证token值
                #查询所有的线上的并且创建人id为create_user_id的资讯
                return response(success,None, [each.as_dict() for each in self.db.session.query(InformationModel).filter_by(create_user_id=create_user_id).all()])
            return response(token_invalid,None,None)
        except Exception as er:
            return response(error,er,None)


class getInformationlistByState(Resource):
    def __init__(self, db, auth=None):
        self.db = db
    
    @swagger.operation(
        notes='通过未上线查询资讯',
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def get(self,token):
        try:
           
            if(verifytoken(token)):#验证token值
                #查询所有的未审核的资讯
                return response(success,None, [each.as_dict() for each in self.db.session.query(InformationModel).filter_by(state=0).all()])
            return response(token_invalid,None,None)
        except Exception as er:
            return response(error,er,None)

# """
# 点赞
# """
class supporting(Resource):
    def __init__(self,db,auth=None):
        self.db = db
    
    @swagger.operation(
        notes='点赞',
        parameters=[
            {
            "name": "support_user_id",
            "description": "点赞人id",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "information_id",
            "description": "资讯id",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "create_user_id",
            "description": "创建人id",
            "dataType": 'string',
            "paramType": "form"
          },
    
        {
            "name": "token",
            "description": "user_token",
            "dataType": 'string',
            "paramType": "form"
          },
      ],
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def post(self):
        try:
            args = request.form
            if(verifytoken(args['token'])):#验证token
                #查询用户是否已经点过赞了
                if(self.db.session.query(SupportModel).filter_by(information_id=args['information_id'],support_user_id = args['support_user_id']).first()==None):
                    #向数据库插入点赞数据
                    self.db.session.add(
                        SupportModel(
                            support_user_id=args['support_user_id'],
                            information_id=args['information_id'],               
                            create_user_id=args['create_user_id'],                
                            update_at=timestamp(),
                            create_at=timestamp()
                        )
                    )
                    #对应的资讯的点赞数+1
                    information_obj = self.db.session.query(InformationModel).filter_by(id = args['information_id']).first()
                    information_obj.support += 1
                    #对应的用户的获赞数+1
                    user_obj = self.db.session.query(UserModel).filter_by(id = args['create_user_id']).first()
                    user_obj.support +=1 
                    #当用户的获赞数达到1000的时候 用户设置为审核员
                    if(user_obj.support >= 1000):
                        user_obj.examine = 1
                    
                    self.db.session.commit()
                    return response(success,None,None)
                else:
                    return response(error,"已经点赞",None)
            else:
                return response(token_invalid,'登陆超时',None)
        except Exception as er:
            return response(error,er,None)

# """
# 举报
# """
class reporting(Resource):
    def __init__(self,db,auth=None):
        self.db = db
    
    
    @swagger.operation(
        notes='举报',
        parameters=[
            {
            "name": "content",
            "description": "举报内容",
            "dataType": 'string',
            "paramType": "form"
          },
            {
            "name": "information_id",
            "description": "资讯id",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "report_user_id",
            "description": "举报人",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "create_user_id",
            "description": "创建人id",
            "dataType": 'string',
            "paramType": "form"
          },
            
        {
            "name": "token",
            "description": "user_token",
            "dataType": 'string',
            "paramType": "form"
          },
      ],
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def post(self):
        try:
            args = request.form #获取表单数据
            if(verifytoken(args['token'])):#验证token
                #判断用户是否对该资讯举报过了
                if(self.db.session.query(ReportModel).filter_by(report_user_id=args['report_user_id'],information_id=args['information_id']).first()==None):
                    #插入举报数据
                    self.db.session.add(
                        ReportModel(
                            content = args['content'],
                            report_user_id=args['report_user_id'],
                            information_id=args['information_id'],               
                            create_user_id=args['create_user_id'],    
                            examine_state = 0 ,           
                            update_at=timestamp(),
                            create_at=timestamp()
                        )
                    )
                    
                    self.db.session.commit()
                    return response(success,None,None)
                else:
                    return response(error,"已经举报过拉",None)
            else:
                return response(token_invalid,'登陆超时',None)
        except Exception as er:
            return response(error,er,None)

# """
# 踩
# """
# class unSupporting(U):
class unSupporting(Resource):
    def __init__(self,db,auth=None):
        self.db = db
    
    @swagger.operation(
        notes='踩',
        parameters=[
            {
            "name": "unsupport_user_id",
            "description": "踩人id",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "information_id",
            "description": "资讯id",
            "dataType": 'string',
            "paramType": "form"
          },
           {
            "name": "create_user_id",
            "description": "创建人id",
            "dataType": 'string',
            "paramType": "form"
          },
    
        {
            "name": "token",
            "description": "user_token",
            "dataType": 'string',
            "paramType": "form"
          },
      ],
        responseMessages=[
            {
                "code": 201,
                "message": "Created. The URL of the created blueprint should " +
                "be in the Location header"
            },
            {
                "code": 405,
                "message": "Invalid input"
            }
        ])
    def post(self):
        try:
            args = request.form
            if(verifytoken(args['token'])):
                #判断当前用户是否已经有记录
                if(self.db.session.query(UnSupportModel).filter_by(information_id=args['information_id'],unsupport_user_id = args['unsupport_user_id']).first()==None):
                    #向数据库插入数据   
                    self.db.session.add(
                        UnSupportModel(
                            unsupport_user_id=args['unsupport_user_id'],
                            information_id=args['information_id'],               
                            create_user_id=args['create_user_id'],                
                            update_at=timestamp(),
                            create_at=timestamp()
                        )
                    )
                    #对应资讯的获踩数+1
                    information_obj = self.db.session.query(InformationModel).filter_by(id = args['information_id']).first()
                    information_obj.unsupported += 1
                    self.db.session.commit()
                    return response(success,None,None)
                else:
                    return response(error,"已经踩过啦",None)
            else:
                return response(token_invalid,'登陆超时',None)
        except Exception as er:
            return response(error,er,None)
